// 对geoData 数据的json 进行处理
// 因为是json 数据，可以直接引入，所以不需要读流，只需要写入流了
const  fs = require('fs');

let  geoJson = require('./address.geo.js');
geoJson = geoJson.default;
 



function formatAddressJson(addressJson) {
  // 获取所有的 省份
  // 四大直辖市
  var fourCitys = ["北京市","天津市", "重庆市", "上海市"];
  let provinces = [];
  for (let province in addressJson) {
    let provinceObj = {};
    provinceObj.label = province;
    provinceObj.value = province;
    let districts;
    // 拿到省市下面所有的区
    if(fourCitys.find(city => city==  province) ){
      districts = addressJson[province]["市辖区"];
      dealDistricts(provinceObj,"市辖区")
      provinces.push(provinceObj);
    }else{    
      provinceObj.children = [];
      for(let city in addressJson[province]){
        let cityObj = {};
        cityObj.label = city;
        cityObj.value = city;
        provinceObj.children.push(cityObj);
        districts = addressJson[province][city];
        dealDistricts(cityObj,city);        
      }
      provinces.push(provinceObj);
    }
     
   function dealDistricts(provinceObj, cityName){
    provinceObj.children = [];
    for (let district in districts) {
      let districtIndex = provinceObj.children.push({
        label: district,
        value: district,
      });
      let districtObj = provinceObj.children[districtIndex - 1];
      districtObj.children = [];
      // 拿到所有区对应的街道
      let streets = addressJson[province][cityName][district];
      for (let street in streets) {
        districtObj.children.push({
          label: streets[street],
          value: streets[street],
        });
      }
    }
    
  }

   }
  // console.log(provinces);
  return provinces;
}





let result = formatAddressJson(geoJson);
let strResult = JSON.stringify(result);


// console.log(strResult)
fs.writeFile('./address.geoFormation.js', strResult , (err) => {
  if (err) throw err;
  console.log('The file has been saved!');
});

// console.log(result)




